
package com.gp.controller.user;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gp.common.result.JsonResult;
import com.gp.common.utils.CookieUtils;
import com.gp.common.utils.EncryptUtil;
import com.gp.controller.BaseController;
import com.gp.model.dto.UserAccountInfo;
import com.gp.model.dto.UserAddInfo;
import com.gp.model.entity.BaseAibExchangeLogs;
import com.gp.model.entity.BaseUser;
import com.gp.model.entity.BaseUserExtends;
import com.gp.service.IBaseAibExchangeLogsService;
import com.gp.service.IBaseUserExtendsService;
import com.gp.service.IBaseUserService;
import com.gp.service.IBaseUserrelationService;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 弓成龙
 * @since 2017-11-26
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
  @Autowired
  private IBaseUserService userService;
  @Autowired
  private IBaseUserExtendsService extendsService;
  @Autowired
  private IBaseAibExchangeLogsService albService;
  @Autowired
  private IBaseUserrelationService relationService;
  /**
   * 用户信息查询
   * 
   * @param page 查询条件
   * @return 用户信息VO
   */
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ApiOperation(value = "查询用户", httpMethod = "GET")
  public JsonResult listUser(HttpServletRequest request,Page<BaseUser> page) {
    String obj = (String)request.getParameter("page");
    Page<BaseUser> result = userService.listUser(page);
    // 私有信息保密处理
    EncryptUtil.HandlerUserPrivateInfo(page);   
    return renderSuccess("查询成功", result);
  }

  @RequestMapping(value = "/detail", method = RequestMethod.GET)
  @ApiOperation(value = "获取当前的用户的信息", httpMethod = "GET")
  public JsonResult listUser(HttpServletRequest request) {
    BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(request);
    if(user==null) {
      return renderError("您尚未登录");
    }else {
      return renderSuccess("获取成功",userService.selectById(user.getId()));
    }
  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  @ApiOperation(value = "添加用户", httpMethod = "POST")
  public JsonResult addUser(@Valid BaseUser user,String parentId, BindingResult bindingResult) {
    Wrapper<BaseUser> wrapper = new EntityWrapper<BaseUser>();
    wrapper.eq("loginName", user.getLoginName());
    wrapper.eq("loginPassword", user.getLoginPassword());
    Object obj =  userService.selectObj(wrapper);
    //  只用用户不存在，并且所填写的上级分销商存在
    if (null != obj || !userService.isExistsParent(parentId)) {
      return new JsonResult("500", "该用户名已注册,或上级分销商不存在");
    }
    if(! StringUtils.hasLength(user.getNickName())) {
      user.setNickName(user.getLoginName());
    }
    CookieUtils.getRequestInfo(user);
    Long uid = userService.insertUser(user);
    Object id = userService.selectObj(wrapper);
    boolean flag = relationService.insertRelation(Long.parseLong(id+""),parentId);
    return flag ? renderSuccess("执行成功", user) : renderError("添加失败");
  }
  
  @RequestMapping(value = "/addDetail", method = RequestMethod.POST)
  @ApiOperation(value = "添加用户", httpMethod = "POST")
  public JsonResult addDetail(UserAddInfo user,String parentId) {
    Wrapper<BaseUser> wrapper = new EntityWrapper<BaseUser>();
    wrapper.eq("loginName", user.getLoginName());
    wrapper.eq("loginPassword", user.getLoginPassword());
    Object obj =  userService.selectObj(wrapper);
    //  只用用户不存在，并且所填写的上级分销商存在
    if (null != obj || !userService.isExistsParent(parentId)) {
      return new JsonResult("500", "该用户名已注册,或上级分销商不存在");
    }
    if(! StringUtils.hasLength(user.getNickName())) {
      user.setNickName(user.getLoginName());
    }
    BaseUser u= CookieUtils.getSimpleUserInfo(user);
    Long uid = userService.insertUser(u);
    Object id = userService.selectObj(wrapper);
    BaseUserExtends e = CookieUtils.getUserDetailInfo(id,user);
    extendsService.insert(e);
    boolean flag = relationService.insertRelation(Long.parseLong(id+""),parentId);
    return flag ? renderSuccess("执行成功", user) : renderError("添加失败");
  }

  @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json")
  @ApiOperation(value = "编辑用户", httpMethod = "POST")
  public JsonResult updateUser(BaseUser user) {
    // 禁止用户调用此方法修改用户名密码
    user.setLoginName(null);
    user.setLoginPassword(null);
    user.setLastModifiedTime(new Date());
    boolean result = userService.updateById(user);
    return result ? renderSuccess("修改成功", result) : renderError("修改失败");
  }

  @RequestMapping(value = "/del/{id}", method = RequestMethod.POST)
  @ApiOperation(value = "删除用户", httpMethod = "POST")
  public JsonResult delUser(@PathVariable @NotNull Long id) {
    boolean result = userService.deleteById(id);
    return result ? renderSuccess("删除成功", result) : renderError("删除失败");
  }

  /**
   * 查询当前用户的艾乐币交易记录
   * 
   * @return
   */
  @RequestMapping(value = "/alb/record", method = RequestMethod.GET)
  public JsonResult listAlbRecord(HttpServletRequest request) {
    Map<String, Object> columnMap = new HashMap<String, Object>();
    columnMap.put("userid", ((BaseUser) CookieUtils.obtainCurrentUser(request)).getId());
    List<BaseAibExchangeLogs> result = albService.selectByMap(columnMap);
    return result.size() != 0 ? renderSuccess("查询成功", result) : renderError("查询失败");
  }
  
  /**
   * 查询当前用户的账户信息
   * 
   * @return
   */
  @RequestMapping(value = "/account", method = RequestMethod.GET)
  public JsonResult listAccountInfo(HttpServletRequest request) {
    BaseUser user = (BaseUser)CookieUtils.obtainCurrentUser(request);
    UserAccountInfo result = userService.selectAccountInfo(user.getId());
    return renderSuccess("查询成功", result);
  }
  
}
